package cn.longge.controller;

import com.baidu.ueditor.ActionEnter;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class UeditorController {

    @Value("${path}")
    private String path;

    @Value("${path2}")
    private String path2;

    @RequestMapping("/ueditor")
    public String execute(String action, HttpServletRequest request, MultipartFile upfile){
        String json = null;
        if("config".equals(action)){
            json = new ActionEnter(request,request.getServletContext().getRealPath("/")).exec();
        }else if("uploadimage".equals(action)){
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            String originalFilename = upfile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            File finalFile = new File(file,fileName);
            try {
                upfile.transferTo(finalFile);
                json = new JSONObject(resultMap("SUCCESS",originalFilename,upfile.getSize(),fileName,suffix,path2 + File.separator + fileName)).toString();
            } catch (IOException e) {
                e.printStackTrace();
                json = new JSONObject(resultMap("FILE",null,0l,null,null,null)).toString();
            }
        }
        return json;
    }

    private Map<String,Object> resultMap(String state, String original, long size, String title, String type, String url){
        Map<String ,Object> result = new HashMap<String ,Object>();
        result.put("state",state);
        result.put("original",original);
        result.put("size",size);
        result.put("title",title);
        result.put("type",type);
        result.put("url", url);
        return result;
    }

}
